package com.wzt.consumer.service.impl;

import com.wzt.base.config.RabbitMQRegisterConfig;
import com.wzt.base.service.impl.BaseServiceImpl;
import com.wzt.base.util.AjaxResponse;
import com.wzt.base.util.MD5Util;
import com.wzt.base.util.VerificationCodeUtil;
import com.wzt.consumer.domain.LoginInfo;
import com.wzt.consumer.domain.User;
import com.wzt.consumer.dto.RegisterDto;
import com.wzt.consumer.dto.RegisterNoticeDto;
import com.wzt.consumer.mapper.LoginInfoMapper;
import com.wzt.consumer.mapper.UserMapper;
import com.wzt.consumer.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzt
 * @since 2022-09-15
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public AjaxResponse register(RegisterDto registerDto) {
        String mobile = registerDto.getMobile();
        String username = registerDto.getUsername();
        String password = registerDto.getPassword();
        String confirmPassword = registerDto.getConfirmPassword();
        String smsCode = registerDto.getSmsCode();
        // 密码空校验和一致性校验
        if (!password.trim().equals(confirmPassword.trim())) {
            return AjaxResponse.oneResponse().setSuccess(false).setMessage("两次密码不一致！");
        }

        // 注册短信验证码的key
        String key = "register_sms_code_" + mobile;

        // 短信验证码判断
        String smsCodeOfRedis = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(smsCodeOfRedis) || !smsCodeOfRedis.split(":")[0].equals(smsCode)) {
            return AjaxResponse.oneResponse().setSuccess(false).setMessage("短信验证码过期或者错误！");
        }

        // 用户是否存在判断
        User userByDb = userMapper.loadByUsername(username);
        if (userByDb != null) {
            return AjaxResponse.oneResponse().setSuccess(false).setMessage("该用户名对应的用户已经存在，不能注册！");
        }

        // 保存登录信息
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(username);
        loginInfo.setPhone(mobile);
        String salt = VerificationCodeUtil.getComplexRandomString(32);
        salt = "wzt" + salt + "momo";
        String securityPwd = MD5Util.encrypByMd5(password + salt);
        loginInfo.setSalt(salt);
        loginInfo.setPassword(securityPwd);

        loginInfo.setType(LoginInfo.LOGIN_INFO_TYPE_USER);
        loginInfo.setDisable(1);
        loginInfoMapper.insert(loginInfo);

        //3 保存用户信息
        User user = new User();
        BeanUtils.copyProperties(loginInfo, user);
        user.setId(null);
        user.setCreatetime(new Date());
        user.setLogininfoId(loginInfo.getId());
        /**
         * 已注册0 已激活2 禁用-1
         */
        user.setState(2);
        userMapper.insert(user);

        //4 发送注册成功通知（短信或邮件）
        rabbitTemplate.convertAndSend(RabbitMQRegisterConfig.EXCHANGE_TOPICS_INFORM,
                "inform.sms",
                new RegisterNoticeDto(mobile,"收到短信通知：你好！你注册的账号已经完成，可以正常使用了！"));
        rabbitTemplate.convertAndSend(RabbitMQRegisterConfig.EXCHANGE_TOPICS_INFORM,
                "inform.email",
                new RegisterNoticeDto(mobile,"收到邮件通知：你好！你注册的账号已经完成，可以正常使用了！"));
        return AjaxResponse.oneResponse();
    }

    @Override
    public AjaxResponse logout(String token) {
        redisTemplate.delete(token);
        return AjaxResponse.oneResponse();
    }
}
